<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { $t } from '@vben/locales';
import { createCompGroupApi, updateCompGroupApi } from '#/api/competition/competitionCtgr';
import { Info } from '@vben/icons';

const props = defineProps({
  modelValue: { type: Boolean, required: true },
  formData: { type: Object, default: () => ({ name: '', compId: '', introduction: '', personCount: 5, realName: '', registrationInstructions: '' }) },
  mode: { type: String, default: 'add' }, // 'add' or 'edit'
  parentTreeOptions: { type: Array, default: () => [] }, // 大赛下拉选项
});

const emit = defineEmits(['update:modelValue', 'success', 'cancel']);

const localForm = ref({ name: '', compId: '', introduction: '', personCount: 5, realName: '', registrationInstructions: '' });
const originalForm = ref({ name: '', compId: '', introduction: '', personCount: 5, realName: '', registrationInstructions: '' });
const formRef = ref();
const isConfirming = ref(false); // 标记是否正在确认保存
const loading = ref(false); // 内部loading状态

// 动态错误消息 - 用于7002状态码错误处理
const nameFieldError = ref('');

// 自定义name字段验证器
const validateName = (_rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error($t('common.inputPhTxt')));
    return;
  }
  if (nameFieldError.value) {
    callback(new Error(nameFieldError.value));
    return;
  }
  callback();
};

const rules = {
  name: [
    { required: true, message: $t('common.inputPhTxt'), trigger: 'blur' },
    { validator: validateName, trigger: 'blur' }
  ],
  compId: [
    { required: true, message: $t('common.selectPhTxt'), trigger: 'blur' },
  ],
  realName: [
    { required: true, message: $t('common.selectPhTxt'), trigger: 'blur' },
  ],
  personCount: [
    {
      required: true,
      type: 'number',
      min: 1,
      max: 100,
      message: '请输入1-100之间的正整数',
      trigger: 'blur'
    }
  ],
};

// 计算确定按钮是否可点击
const isFormValid = computed(() => {
  if (!localForm.value) return false;
  const name = localForm.value.name || '';
  const compId = localForm.value.compId || '';
  const realName = localForm.value.realName;
  return name.trim() !== '' && compId !== '' && realName !== '';
});

// 检查表单是否有修改
const isFormChanged = computed(() => {
  if (!localForm.value || !originalForm.value) return false;
  return JSON.stringify(localForm.value) !== JSON.stringify(originalForm.value);
});

watch(() => props.formData, (val: any) => {
  const defaultData = { name: '', compId: '', introduction: '', personCount: 5, realName: '', registrationInstructions: '' };
  localForm.value = { ...defaultData, ...val };
  originalForm.value = { ...defaultData, ...val };
  isConfirming.value = false; // 重置确认状态
  nameFieldError.value = ''; // 重置错误状态
}, { immediate: true });

// 监听name字段变化，清除错误状态
watch(() => [localForm.value.name, localForm.value.compId], () => {
  if (nameFieldError.value) {
    nameFieldError.value = '';
    // 重新验证name字段以清除错误显示
    if (formRef.value) {
      formRef.value.validateField('name');
    }
  }
});

// API调用处理
const handleApiCall = async (formData: any) => {
  try {
    if (props.mode === 'add') {
      const { name, introduction, compId, personCount, realName, registrationInstructions } = formData;
      await createCompGroupApi({ name, introduction, compId, personCount, realName, registrationInstructions });
      ElMessage.success($t('competition.addSuccess'));
    } else {
      const { id, name, introduction, compId, personCount, realName, registrationInstructions } = formData;
      await updateCompGroupApi({ id, name, introduction, compId, personCount, realName, registrationInstructions });
      ElMessage.success($t('competition.updateSuccess'));
    }

    // 成功后关闭弹窗并通知父组件刷新
    emit('update:modelValue', false);
    emit('success');

  } catch (error) {
    // 检查是否是表单验证错误（状态码7002）
    if ((error as any)?.status == 7002) {
      // 设置name字段的错误消息
      nameFieldError.value = (error as any)?.message || $t('competition.duplicateGroupNameError');

      // 触发name字段的验证以显示错误
      if (formRef.value) {
        formRef.value.validateField('name');
      }

      // 不抛出错误，让用户可以修改后重新提交
      return;
    }

    // 其他错误继续抛出
    throw error;
  }
};

const handleConfirm = async () => {
  if (!isFormValid.value) return;

  try {
    // 表单验证
    await formRef.value.validate();

    loading.value = true;
    isConfirming.value = true;

    await handleApiCall(localForm.value);

  } catch (error) {
    if (error !== 'cancel') {
      // 移除 console.error 调试语句
    }
  } finally {
    loading.value = false;
    isConfirming.value = false;
  }
};

const handleCancel = async () => {
  isConfirming.value = false;
  // 没有修改，直接关闭
  formRef.value?.resetFields && formRef.value.resetFields();
  emit('update:modelValue', false);
  emit('cancel');
};
</script>
<template>
  <ElDialog :model-value="modelValue" :title="mode === 'add' ? $t('competition.addGroup') : $t('competition.editGroup')"
    width="600px" @close="handleCancel" align-center>
    <ElForm ref="formRef" :model="localForm" :rules="rules" label-width="100px">
      <ElFormItem prop="name" :label="$t('competition.groupName')">
        <ElInput v-model="localForm.name" maxlength="50" :placeholder="$t('common.inputPhTxt')" />
      </ElFormItem>
      <ElFormItem prop="compId" :label="$t('competition.belongCompetition')">
        <ElSelect v-model="localForm.compId" :placeholder="$t('common.selectPhTxt')" style="width: 100%">
          <ElOption v-for="item in parentTreeOptions" :key="(item as any).value" :label="(item as any).label"
            :value="(item as any).value" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem prop="realName" label-width="110px" class="relative">
        <template #label>
          <ElTooltip :content="$t('competition.realNameTooltip')" placement="top">
            <ElIcon class="absolute left-[-10px] top-2">
              <Info />
            </ElIcon>
          </ElTooltip>
           {{ $t('competition.isRealName') }}
        </template>
        <ElRadioGroup v-model="localForm.realName">
          <ElRadio :value="true">{{ $t('competition.yes') }}</ElRadio>
          <ElRadio :value="false">{{ $t('competition.no') }}</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem class="relative">
        <template #label>
          <ElTooltip :content="$t('competition.registrationInstructionsTooltip')" placement="top">
            <ElIcon class="absolute left-[10px] top-2">
              <Info />
            </ElIcon>
          </ElTooltip>
          {{ $t('competition.registrationInstructions') }}
        </template>
        <ElInput v-model="localForm.registrationInstructions" type="textarea" :rows="3"
          :placeholder="$t('common.inputPhTxt')" maxlength="200" show-word-limit />
      </ElFormItem>
      <ElFormItem :label="$t('competition.introduction')">
        <ElInput v-model="localForm.introduction" type="textarea" :rows="3" :placeholder="$t('common.inputPhTxt')"
          maxlength="200" show-word-limit />
      </ElFormItem>
      <ElFormItem prop="personCount" :label="$t('competition.personCount')">
        <ElInputNumber
          v-model="localForm.personCount"
          :precision="0"
          :min="1"
          :max="100"
          :step="1"
          :controls="true"
          style="width: 100%"
        />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="handleCancel">{{ $t('common.cancel') }}</ElButton>
      <ElButton type="primary" @click="handleConfirm" :loading="loading" :disabled="!isFormValid">
        {{ $t('common.confirm') }}
      </ElButton>
    </template>
  </ElDialog>
</template>
